package com.xsjiong.learning;
import java.io.*;
import java.util.*;

public class HandwritingRecognizer {
	public static void main(String[] args) throws Throwable {
		final String P="/sdcard/AppProjects/MNIST.nn";
		final String P1="/sdcard/AppProjects/train-images";
		final String P2="/sdcard/AppProjects/train-labels";
		final int S=28 * 28;

		NeuralNetwork net=null;

		if (true) {
			FileInputStream in=new FileInputStream(P);
			DataInputStream din=new DataInputStream(in);
			net = new NeuralNetwork(din);
			din.close();
			in.close();
		} else {
			net = new NeuralNetwork(0, false, new NeuralNetwork.ActivationFunction[]{
										NeuralNetwork.ActivationFunction.Sigmoid,
										NeuralNetwork.ActivationFunction.Sigmoid,
										NeuralNetwork.ActivationFunction.None
									}, new int[]{S, 200, 50, 10});
			//net.RandomizeWeight();
		}

		byte[] buf=new byte[S];
		double[] tin=new double[S];
		double[][][] w=net.CreateEmptyWeight();
		double costa,costb;
		double[] tout=new double[10];

		net.Rate = 0.2;
		int tt;
		int ans;
		int tot;

		for (int aa=0;aa < 5;aa++) {
			tot = 0;
			tt = 0;
			FileInputStream ifin=new FileInputStream(P1);
			DataInputStream iin=new DataInputStream(ifin);
			iin.readInt();
			int T=iin.readInt();
			iin.readInt();
			iin.readInt();
			FileInputStream lfin=new FileInputStream(P2);
			DataInputStream lin=new DataInputStream(lfin);
			lin.readInt();
			lin.readInt();
			for (int i=0,j;i < 100;i++) {
				iin.read(buf);
				for (j = 0;j < S;j++) tin[j] = buf[j];
				ans = lin.read();
				tout[ans] = 1;
				net.Input(tin);
				if (net.MaxIndex() == ans) tt++;
				//net.CopyWeight(w);
				costa = net.Cost(tout);
				net.Fit(tout);
				net.Input(tin);
				costb = net.Cost(tout);
				/*if (true) {
					if (costb <= costa) net.Rate *= 1.01;
					else {
						net.SetWeight(w);
						net.Rate /= 2;
					}
				} else {
					if (costb > costa) {
						net.SetWeight(w);
						//costb=costa;
					}
				}*/
				tout[ans] = 0;
				System.out.printf("%.6f\n", costa);
				if (costa >= 1) tot++;
				//System.out.println(Arrays.toString(net.GetOutput()));
				//if (j % 100 == 0) System.out.println(j);
			}
			iin.close();
			ifin.close();
			lin.close();
			lfin.close();
			//System.out.println("完成！");
			//System.out.println("大型差错: " + tot);
			System.out.println("正确次数: " + tt + " " + net.Rate);
		}

		FileOutputStream out=new FileOutputStream(P);
		BufferedOutputStream bout=new BufferedOutputStream(out);
		DataOutputStream dos=new DataOutputStream(bout);
		net.WriteTo(dos);
		dos.close();
		bout.close();
		out.close();

		System.out.println("OK");
	}
}
